<template>
  <section class="auth">
    <h1 class="title">登录</h1>
    <form class="form" @submit.prevent="onSubmit">
      <label>
        <span>用户名</span>
        <input v-model="username" type="text" autocomplete="username" />
      </label>
      <label>
        <span>密码</span>
        <input v-model="password" type="password" autocomplete="current-password" @input="onPasswordInput" />
      </label>
      <p v-if="error" class="error">{{ error }}</p>
      <button type="submit">登录</button>
      <p class="hint">没有账号？<a @click.prevent="goRegister" href="/register">去注册</a></p>
    </form>
  </section>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { login } from '@/utils/auth'

const router = useRouter()
const username = ref('')
const password = ref('')
const error = ref('')

// 密码输入监听器
function onPasswordInput() {
  // 可以在这里添加额外的密码输入处理逻辑
  // 例如清除错误信息等
  if (error.value) {
    error.value = ''
  }
}

async function onSubmit() {
  error.value = ''
  try {
    await login(username.value, password.value)
    router.push('/')
  } catch (e) {
    error.value = e?.message || '登录失败'
  }
}
function goRegister() { router.push('/register') }
</script>

<style scoped>
.auth { max-width: 420px; margin: 0 auto; }
.title { margin: 12px 4px 12px; font-size: 24px; font-weight: 800; }
.form { display: grid; gap: 12px; }
label { display: grid; gap: 6px; }
input { padding: 10px 12px; border: 1px solid #e5e7eb; border-radius: 10px; background: #fff; color: #374151; }
button { padding: 10px 14px; border: none; border-radius: 999px; background: #00a1d6; color: #fff; cursor: pointer; }
.error { color: #d14343; }
.hint { color: #6b7280; }
.hint a { color: #00a1d6; cursor: pointer; }
</style>